package com.huitone.gddw.service.impl.monitoring;


import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;



import com.huitone.gddw.dao.entity.AlarmReceiveUser;


import com.huitone.gddw.dao.entity.ObjItem;
import com.huitone.gddw.dao.entity.ObjItemProperty;
import com.huitone.gddw.dao.entity.ObjectManagement;
import com.huitone.gddw.dao.entity.ReturnedValue;
import com.huitone.gddw.dao.entity.TomcatItem;
import com.huitone.gddw.dao.entity.Trigger;
import com.huitone.gddw.dao.monitoring.ObjectItemDao;
import com.huitone.gddw.service.TomcatItemService;
import com.huitone.gddw.utils.MonitoringResult;
import com.huitone.gddw.utils.MonitoringUtils;
import com.huitone.gddw.utils.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 保存、查找tomcat监控数据service实现类
 * @author lipengfei
 *
 */
@Service("tomService")
public class TomcatItemServiceImpl implements TomcatItemService{
	
	private final static Logger LOGGER = Logger.getLogger(TomcatItemServiceImpl.class);
	
	
	@Resource
	private ObjectItemDao objDao;
	
	/**
	 * 获取tomcat对象集合
	 */
	@Override
	public MonitoringResult<List<TomcatItem>> loadTomcatItem(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<List<TomcatItem>> result = new MonitoringResult<List<TomcatItem>>();
		
		//用于存放TomcatItem对象的集合
		List<TomcatItem> tomcatList = new ArrayList<TomcatItem>();
		//传入页码，在数据库全部对象表中查找Tomcat类型的数据
		Map<String, Object> map = MonitoringUtils.getMap(value.getPageNo(),value.getPageSize());
		map.put("objType", "tomcat");
		List<ObjectManagement> objList = objDao.selectObjAllByObjType(map);
		//对查到啊的tomcat对象数据进行遍历获得子项全部数据并加入list集合
		for(ObjectManagement obj:objList){
			if(obj!=null){
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "info");
				ObjItem objItem = objDao.selectObjItemByItemName(objmap);
				if(objItem != null){
					List<Map<String, String>> proList = objDao.selectValue(objItem.getItemId());
					TomcatItem tomItem = new TomcatItem();
					System.out.println(proList);
					for (Map<String, String> item:proList) {
						if(item.get("KEY").equals("name")){
							tomItem.settName(item.get("VALUE"));
						}else if(item.get("KEY").equals("ip")){
							tomItem.settIp(item.get("VALUE"));
						}else if(item.get("KEY").equals("port")&& !item.get("VALUE").isEmpty()){
							tomItem.settPort(StringUtils.strToInteger(item.get("VALUE")));
						}else if(item.get("KEY").equals("ver")&& !item.get("VALUE").isEmpty()){
							tomItem.settVersions(StringUtils.strToDouble(item.get("VALUE")));
						}else if(item.get("KEY").equals("jvm")&& !item.get("VALUE").isEmpty()){
							tomItem.setJvmVersions(StringUtils.strToDouble(item.get("VALUE")));
						}else if(item.get("KEY").equals("os")){
							tomItem.setOs(item.get("VALUE"));
						}			
					}
					List<Integer> list = objDao.loadLastCollectTime(objItem.getItemId());
							int j= 0;
							for(Integer i:list){
								if(i>j){
									j=i;
								}
							}
					tomItem.setLastCollectTime(new Date(j*1000));
					tomItem.settName(obj.getObjName());
					tomItem.setAlarmAmount(objDao.getNowExcptionCount(objmap));
					tomcatList.add(tomItem);
					result.setStatus(0);
					result.setMsg("tomcat信息加载成功");
				}else{
					TomcatItem tomItem = new TomcatItem();
					tomItem.settName(obj.getObjName());
					tomcatList.add(tomItem);
					result.setStatus(0);
					result.setMsg("tomcat信息加载成功");
				}
			}else{
				result.setMsg("没有监控对象");
			}
		}
		
		//对数据结果进行包装传送
		result.setPageNo(value.getPageNo());
		result.setTotalCount(objDao.selectObjCountByType(map));
		result.setPageSize(5);
		result.setData(tomcatList);
		return result;
	}
	/**
	 * 获取一条tomcat对象
	 * @return
	 */
	@Override
	public MonitoringResult<Map<String, Object>> addIndex() {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存放数据
		Map<String, Object> resultMap = new HashMap<>();
		//存放搜索参数
		Map<String, String> map = new HashMap<>();
		map.put("objType","tomcat");
		//tomcat名称集合
		List<ObjectManagement> hostNameList = objDao.selectObjName(map);
		if(!hostNameList.isEmpty()){
			result.setStatus(0);
			result.setMsg("tomcat名称获取成功");
		}
		resultMap.put("hostnames", hostNameList);
		result.setData(resultMap);
		return result;
	}
	@Override
	public MonitoringResult<Map<String, Object>> showIndex(ReturnedValue value) {
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存放结果数据
		Map<String, Object> resultMap = new HashMap<String, Object>();
				
		//保存需要的参数
		Map<String, String> map = new HashMap<>();
		map.put("objId", value.getHostId());
		map.put("itemName", "info");
		//获取指标的名称和告警接受人
		List<ObjItemProperty> indexnamelist = new ArrayList<ObjItemProperty>();
		List<AlarmReceiveUser> alarmUserList = objDao.selectAlarmReceiveUser(value.getHostId());
				
		ObjItem objItem = objDao.selectObjItemByItemName(map);
		if(objItem !=null){
			List<ObjItemProperty> indexname = objDao.getIndexName(objItem.getItemId());
				if(!indexname.isEmpty()){
					indexnamelist.addAll(indexname);
					result.setStatus(0);
					result.setMsg("主机监控指标名称获取成功,告警接收人获取成功");
				}else{
					LOGGER.info("没有需要添加的redis监控指标");
				}
			}else{
				LOGGER.info("没有找到redis基本信息");
			}
			resultMap.put("indexnames", indexnamelist);
			resultMap.put("alarmusers", alarmUserList);
			result.setData(resultMap);	
			return result;
	}
	@Override
	public MonitoringResult<TomcatItem> save(ReturnedValue value) {
		MonitoringResult<TomcatItem> result = new MonitoringResult<TomcatItem>();
		try {
			if(value.getIndex()!=null && value.getAlarmRecUser()!=null){
				JSONArray indexja =JSONArray.fromObject(URLDecoder.decode(value.getIndex(),"UTF-8")); 
				JSONArray alarmja = JSONArray.fromObject(URLDecoder.decode(value.getAlarmRecUser(),"UTF-8"));
					for(int i = 0;i< indexja.size();i++){
						JSONObject indexjb = indexja.getJSONObject(i);
								if(!indexjb.getString("alarmLevel").isEmpty()){
									//保存指标信息
									ObjItemProperty objItemProperty = new ObjItemProperty();
									objItemProperty.setKeyNameCn(indexjb.getString("indexName"));
									objItemProperty.setKeyId(indexjb.getString("keyId"));
//									if(!indexjb.getString("quantity").isEmpty()){
//										objItemProperty.setQuantity(StringUtils.strToDouble(indexjb.getString("quantity")));
//									}
//									objItemProperty.setIndexUnit(indexjb.getString("unit"));
									objDao.updateIndex(objItemProperty);
									//保存告警信息
									Trigger trigger = new Trigger();
									String triggerId = StringUtils.uuid();
									trigger.setTriggerId(triggerId);
									trigger.setItemId(objDao.selectItemIdByKeyId(indexjb.getString("keyId")));
									trigger.setKeyId(indexjb.getString("keyId"));
									if(!indexjb.getString("upperLimit").isEmpty()){
										trigger.setUpperLimit(StringUtils.strToDouble(indexjb.getString("upperLimit")));
									}
									if(!indexjb.getString("lowerLimit").isEmpty()){
										trigger.setLowerLimit(StringUtils.strToDouble(indexjb.getString("lowerLimit")));
										
									}
//									trigger.setAlarmLevel(StringUtils.strToInteger(indexjb.getString("alarmLevel")));
//									trigger.setSustainTime(indexjb.getString("sustainTime"));
									trigger.setIndexDesc(indexjb.getString("indexDesc"));
									objDao.saveAlarm(trigger);
									//保存告警接受人
									for(int j = 0;j<alarmja.size();j++){
										JSONObject alarmjb = alarmja.getJSONObject(j);
										AlarmReceiveUser user = new AlarmReceiveUser();
										user.setRceId(alarmjb.getString("rceId"));
										user.setObjId(value.getHostId());
										user.setReceiveUser(alarmjb.getString("receiveUser"));
										user.setPhone(alarmjb.getString("phone"));
										user.setEmail(alarmjb.getString("email"));
										user.setUserType(alarmjb.getString("userType"));
										user.setRecAlarmLevel1(alarmjb.getString("recAlarmLevel1"));
										
										user.setRecAlarmLevel2(alarmjb.getString("recAlarmLevel2"));
										
										user.setRecAlarmLevel3(alarmjb.getString("recAlarmLevel3"));
										
										objDao.updateUser(user);
									}
									
							}else{
								result.setMsg("必须添加告警信息");
								return result;
							}
						}
					result.setStatus(0);
					result.setMsg("保存成功");
					return result;

				}else{
					result.setMsg("监控指标或接收人不能为空,保存失败");
				}
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("保存失败");
		}
		return result;
	}
	@Override
	public MonitoringResult<Map<String, Object>> showInfo(ReturnedValue value) {
		// TODO Auto-generated method stub
		//用于传递数据结果的方法
		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
		//用于存放结果数据
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectManagement obj= objDao.selectObjById(value.getHostId());
		//对查到啊的tomcat对象数据进行判断并获得子项全部数据并加入list集合
		TomcatItem tomItem = new TomcatItem();
		List<String> reslist = new ArrayList<String>(); 
		List<String> memlist = new ArrayList<String>(); 
		try {
		if(obj!=null){
				Map<String, String> objmap = new HashMap<>();
				objmap.put("objId", obj.getObjId());
				objmap.put("itemName", "info");
				ObjItem objItem = objDao.selectObjItemByItemName(objmap);
				if(objItem != null){
					List<Map<String, String>> proList = objDao.selectValue(objItem.getItemId());
					System.out.println(proList);
					for (Map<String, String> item:proList) {
						if(item.get("KEY").equals("name")){
							tomItem.settName(item.get("VALUE"));
						}else if(item.get("KEY").equals("ip")){
							tomItem.settIp(item.get("VALUE"));
						}else if(item.get("KEY").equals("port")&& !item.get("VALUE").isEmpty()){
							tomItem.settPort(StringUtils.strToInteger(item.get("VALUE")));
						}else if(item.get("KEY").equals("ver")&& !item.get("VALUE").isEmpty()){
							tomItem.settVersions(StringUtils.strToDouble(item.get("VALUE")));
						}else if(item.get("KEY").equals("jvm")&& !item.get("VALUE").isEmpty()){
							tomItem.setJvmVersions(StringUtils.strToDouble(item.get("VALUE")));
						}else if(item.get("KEY").equals("os")){
							tomItem.setOs(item.get("VALUE"));
						}else if(item.get("KEY").equals("mem")&& !item.get("VALUE").isEmpty()){
							tomItem.setMem(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("availablemem")&& !item.get("VALUE").isEmpty()){
							tomItem.setAvailableMem(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("usemem")&& !item.get("VALUE").isEmpty()){
							tomItem.setUseMem(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("maxthreads")&& !item.get("VALUE").isEmpty()){
							tomItem.setMaxThreads(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("threads")&& !item.get("VALUE").isEmpty()){
							tomItem.setThreads(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("reqs")&& !item.get("VALUE").isEmpty()){
							tomItem.setReqs(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("reqsuc")&& !item.get("VALUE").isEmpty()){
							tomItem.setReqsuc(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("reqfail")&& !item.get("VALUE").isEmpty()){
							tomItem.setReqfail(StringUtils.strToInteger(item.get("VALUE")));			
						}else if(item.get("KEY").equals("reqmaxtime")&& !item.get("VALUE").isEmpty()){
							tomItem.setReqmaxtime(StringUtils.strToInteger(item.get("VALUE")));			
						}
					}
					List<Integer> list = objDao.loadLastCollectTime(objItem.getItemId());
							int j= 0;
							for(Integer i:list){
								if(i>j){
									j=i;
								}
							}
					tomItem.setLastCollectTime(new Date(j*1000));
					tomItem.settName(obj.getObjName());
					tomItem.setAlarmAmount(objDao.getNowExcptionCount(objmap));
				}else{
					tomItem.settName(obj.getObjName());
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Map<String, Object> map = new HashMap<>();
				map.put("itemId", objItem.getItemId());
				map.put("keyName", "resptime");
				map.put("startTime",sdf.parse(value.getStartTime()).getTime()/1000);
				map.put("endTime", sdf.parse(value.getEndTime()).getTime()/1000);
				reslist = objDao.selectHistoryValue(map);
				map.put("keyName", "memrate");
				memlist = objDao.selectHistoryValue(map);
				result.setMsg("信息获取成功");
				result.setStatus(0);
			}else{
				result.setMsg("没有监控对象");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		resultMap.put("tomInfo", tomItem);
		resultMap.put("resptime", reslist);
		resultMap.put("memrate", memlist);
		result.setData(resultMap);
		return result;
	}
//	@Override
//	public MonitoringResult<Map<String, Object>> selectInfo(ReturnedValue value) {
//		// TODO Auto-generated method stub
//		return null;
//	}
	
	
//	@SuppressWarnings("null")
//	@Override
//	public MonitoringResult<Map<String, Object>> updata(ReturnedValue value) {
//		//用于传递数据结果的方法
//		MonitoringResult<Map<String, Object>> result = new MonitoringResult<Map<String, Object>>();
//		//存放参数
//		Map<String, String> map = new HashMap<>();
//		map.put("objId", value.getHostId());
//		map.put("itemName", "info");
//		//用于存储数据结果map
//		Map<String, Object> mainMap = new HashMap<>();
//		//存放指标的集合
//		List<Index> indexList = new ArrayList<Index>();
//		//存放告警接受人的集合
//			List<AlarmReceiveUser> userList =new ArrayList<AlarmReceiveUser>();
//				Index index = new Index();
//				ObjectManagement obj = objDao.selectObjById(map);
//				if(obj!=null){
//					ObjItem objItem = objDao.selectObjItemByItemName(map);
//					if(objItem !=null){
//						List<ObjItemProperty> objProperty = objDao.selectProperty(objItem.getItemId());
//						for(ObjItemProperty itemPro:objProperty){
//							map.put("itemId", objItem.getItemId());
//							map.put("keyId", itemPro.getKeyId());
//							Trigger trigger= objDao.selectAlarm(map);
//							
//								index.setIndexName(itemPro.getKeyName());
//								index.setQuantity(itemPro.getQuantity());
//								index.setUnit(itemPro.getIndexUnit());
//								index.setAlarmLevel(StringUtils.intToString(trigger.getAlarmLevel()));
//								index.setUpperLimit(trigger.getUpperLimit());
//								index.setLowerLimit(trigger.getLowerLimit());
//								index.setSustainTime(trigger.getSustainTime());
//								indexList.add(index);
//								List<AlarmReceiveUser> recList = objDao.selectAlarmReceiveUser(trigger.getTriggerId());
//								for(AlarmReceiveUser rec:recList){
//									if(userList!=null){
//										for(AlarmReceiveUser user:userList){
//											if(!(user.getRceId().equals(rec.getRceId()))){
//												userList.add(rec);
//											}
//										}
//									}else{
//										userList.add(rec);
//									}
//									
//									
//								
//							}
//							mainMap.put("index", indexList);
//							mainMap.put("receiver", userList);
//							result.setStatus(0);
//							result.setMsg("tomcat监控指标信息获取成功");
//							result.setData(mainMap);
//							return result;
//						}
//						
//					}else{
//						MonitoringUtils.MonitoringException("该tomcat还没添加指标监控");
//					}
//				}else{
//					MonitoringUtils.MonitoringException("该tomcat不存在");
//				}
//				mainMap.put("index", indexList);
//				mainMap.put("receiver", userList);
//				result.setData(mainMap);
//				return result;
//	}
//
//	

}
